
<template>
  <div id="loginContainer">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>欢迎使用后台管理系统</span>
      </div>
      <el-form
        :model="formData"
        status-icon
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        label-position="left"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            type="text"
            v-model="formData.username"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            type="password"
            v-model="formData.password"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')"
            >提交</el-button
          >
          <el-button @click="resetForm('ruleForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { login } from "../APi/users";
import { setToken } from "../Utils/auth";

export default {
  data() {
    return {
      rules: {
        username: [
          { required: true, message: "用户名不能为空", trigger: "blur" },
        ],
        password: [
          { required: true, message: "密码不能为空", trigger: "blur" },
        ],
      },
      formData: {
        username: "",
        password: "",
      },
    };
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          //调用登录时的请求
          login(this.formData)
            .then((res) => {
               console.log(res);

              var dataInfo = res.data;
              var currentUser = this.formData.username;
               
              //判断是否请求成功
              if (res.code == 1000) {

                //注册token
                setToken(dataInfo.token, dataInfo.freshToken, currentUser);

                //跳转到首页路由
                this.$router.push("/");
              } else {
                //弹出报错提示
                this.$message({
                  type: "error",
                  message: res.msg,
                });
              }
            })
            .catch((err) => {
              console.log(err);
            });
        } else {
          console.log("提交错误");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
  },
};
</script>

<style scoped>
.box-card {
  background-color: #eeee;
  color: aqua;
  font-size: 30px;
  font-weight: bold;
  margin: auto;

  width: 480px;
}
#loginContainer {
  margin: 0;
  background-image: url(../assets/img/bj001.jpg);
  height: 100vh;
  padding-top: 200px;
  width: auto;
  /* background-color: blue; */
}
</style>